package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.Listener.SubjectExcelListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.entity.subject.OneSubject;
import com.atguigu.eduservice.entity.subject.TwoSubject;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author 李川
 * @since 2020-05-14
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    //实现课程分类
    @Override
    public void saveSubject(MultipartFile file,EduSubjectService eduSubjectService) {
        try{
            //文件输入流
            InputStream in = file.getInputStream();
            //调用方法进行读取
            EasyExcel.read(in, SubjectData.class,new SubjectExcelListener(eduSubjectService)).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    //查询出来所有的一级分类和二级分类
    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        //查询1级分类
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("parent_id",0);
        List<EduSubject> eduSubjectsOne = baseMapper.selectList(wrapper);


        //查询2级分类
        QueryWrapper<EduSubject> wrapperTwo=new QueryWrapper<>();
        wrapperTwo.ne("parent_id","0");
        List<EduSubject> eduSubjectsTwo = baseMapper.selectList(wrapperTwo);

        //创建list集合
        List<OneSubject> finalSubjectLsit=new ArrayList<>();
        //遍历每个一级分类值
        for(int i=0;i<eduSubjectsOne.size();i++){
            EduSubject eduSubject=eduSubjectsOne.get(i);

            //把值取出换到第二个集合
            OneSubject oneSubject=new OneSubject();
            BeanUtils.copyProperties(eduSubject,oneSubject);
            finalSubjectLsit.add(oneSubject);

            //创建list集合
            List<TwoSubject> twoSubjectList=new ArrayList<>();
            //遍历每个二级分类值
            for(int j=0;j<eduSubjectsTwo.size();j++){
                EduSubject eduSubject2=eduSubjectsTwo.get(j);
                if(eduSubject2.getParentId().equals(eduSubject.getId())){
                    TwoSubject twoSubject=new TwoSubject();
                    BeanUtils.copyProperties(eduSubject2,twoSubject);  //把值给封装的二级分类的类
                    twoSubjectList.add(twoSubject);
                }
            }
            //把所有二级分类给一级分类
            oneSubject.setChildren(twoSubjectList);
        }
        return finalSubjectLsit;
    }
}
